package com.dek.seckill.service;

import com.dek.seckill.common.redis.KeyPrefix;
import com.dek.seckill.common.redis.RedisService;
import com.dek.seckill.common.redis.UserKey;
import com.dek.seckill.common.util.CodeMsg;
import com.dek.seckill.common.util.MD5Util;
import com.dek.seckill.common.util.UUIDUtil;
import com.dek.seckill.entity.User;
import com.dek.seckill.mapper.UserMapper;
import com.dek.seckill.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;

@Service
public class UserService {

    private static final String COOKIE_NAME_TOKEN = "11";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    public User getByMobile(String mobile) {
        return userMapper.getByMobile(mobile);
    }


    @Transactional
    public int insert(User user) {
        return userMapper.insert(user);
    }

    public CodeMsg login(LoginVO loginVO) {
        if (loginVO == null) {
            return CodeMsg.SERVER_ERROR;
        }
        String mobile = loginVO.getMobile();
        String formPass = loginVO.getPassword();
        User user = getByMobile(mobile);
        if (user == null) {
            return CodeMsg.SERVER_ERROR;
        }
        String dbPass = user.getPassword();
        String saltDB = user.getSalt();
        String calcPass = MD5Util.formPassToDBPass(formPass, saltDB);
        if (calcPass.equals(dbPass)) {
            return CodeMsg.SERVER_ERROR;
        }

        String token = UUIDUtil.uuid();
        redisService.set(UserKey.token, token, user);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(UserKey.token.expireSeconds());

        return CodeMsg.SUCCESS;
    }
}
